﻿using System;
using System.Web;

namespace ELearning.Common.Buffer
{
    /// <summary>
    /// Cookie辅助类
    /// </summary>
    public class CookieHelper
    {
        /// <summary>
        /// 清除指定Cookie
        /// </summary>
        /// <param name="cookieName">cookieName</param>
        public static void RemoveCookie(string cookieName)
        {
            var cookie = HttpContext.Current.Request.Cookies[cookieName];
            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddSeconds(-3);
                HttpContext.Current.Response.Cookies.Set(cookie);
            }
        }

        /// <summary>
        /// 获取指定Cookie值
        /// </summary>
        /// <param name="cookieName">cookieName</param>
        /// <returns></returns>
        public static string GetcookieValue(string cookieName)
        {
            var cookie = HttpContext.Current.Request.Cookies[cookieName];
            var str = string.Empty;
            if (cookie != null)
            {
                str = HttpUtility.UrlDecode(cookie.Value, System.Text.Encoding.UTF8);
            }
            return str;
        }

        /// <summary>
        /// 添加一个Cookie（默认60分钟过期）
        /// </summary>
        /// <param name="cookieName">key</param>
        /// <param name="cookieValue">值</param>
        /// <param name="minutes">分钟数</param>
        public static void SetCookie(string cookieName, string cookieValue, int minutes = 60)
        {
            SetCookie(cookieName, cookieValue, DateTime.Now.AddMinutes(minutes));
        }

        /// <summary>
        /// 添加一个Cookie
        /// </summary>
        /// <param name="cookieName">cookie名</param>
        /// <param name="cookieValue">cookie值</param>
        /// <param name="expires">过期时间 DateTime</param>
        public static void SetCookie(string cookieName, string cookieValue, DateTime expires)
        {
            var cookie = new HttpCookie(cookieName)
            {
                Value = HttpUtility.UrlEncode(cookieValue, System.Text.Encoding.UTF8),
                Expires = expires
            };
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
    }
}
